import java.util.Arrays;

/**
 * @program: leetcode581
 * @author: JCM
 * @create: 2023-03-16 15:24
 * @description:
 **/
public class Main {

    public int findUnsortedSubarray(int[] nums) {
        int len = nums.length;
        int right = -1;
        int left = -1;
        int min = nums[0];
        int max = nums[len-1];
        for(int i = 0; i < len; i++) {
            if(nums[i] < min) {
                right = i;
            }else {
                min = nums[i];
            }
            if(nums[len-i-1] > max) {
                left = len-i-1;
            }else {
                max = nums[len-i-1];
            }
        }
        if(right == -1) return 0;
        return right-left+1;
    }

    /**
     * 先copy一个数组排序，然后比较数字开始发生变化的位置
     * @param nums
     * @return
     */
    public int findUnsortedSubarray1(int[] nums) {
        if(isSorted(nums)) {
            return 0;
        }
        int[] sortNums = new int[nums.length];
        System.arraycopy(nums,0,sortNums,0,nums.length);
        Arrays.sort(sortNums);
        int left = 0;
        int right = nums.length-1;
        while(nums[left] == sortNums[left]) {
            left++;
        }
        while(nums[right] == sortNums[right]) {
            right--;
        }
        return right-left+1;
    }
    public boolean isSorted(int[] nums) {
        for(int i = 1; i < nums.length; i++) {
            if(nums[i] < nums[i-1]) {
                return false;
            }
        }
        return true;
    }
}
